/**
 * Created by godhh on 2016/12/21.
 */
import angular from 'angular';
import 'apiService';
import _ from 'lodash';
import '@yunke/angular-ui/lib/uiRadioArray';
import '@yunke/angular-ui/lib/ykDropdown';
import moment from 'moment';
import 'angular-ui';
import ui from '@yunke/core/ui';
import 'uploader';
import './stock_out_helper';

const app = angular.module('stockOut',
    ['ApiService', 'angular.directive.uiRadioArray', 'angular.directive.ykDropdown', 'ngUI', 'stockOutHelper']);

app.filter('contractType', () => (origin) => {
    return (
        {
            1: '新增',
            2: '增购',
            3: '续签'
        }
    )[origin];
})
    .controller('stockOutCtrl', [
    '$rootScope', '$scope', '$timeout', '$q', 'api', 'mapSnakeCase',
    function ($rootScope, $scope, $timeout, $q, api, mapSnakeCase) {

        const service = api.getService();

        const stockOutType = [
            {
                value: '1',
                text: '直属正常'
            }, {
                value: '2',
                text: '直属特批'
            }, {
                value: '3',
                text: '联营正常'
            }, {
                value: '4',
                text: '联营特批'
            }];

        // 租户类型
        const tenantType = [
            {
                value: '1',
                text: '新租户'
            }, {
                value: '0',
                text: '已有租户'
            }];

        // 直属特批类型
        const directAllowedType = [
            {
                value: '01', //contract_status money_status
                text: '合同未归档'
            }, {
                value: '00',
                text: '合同未归档且款项未回'
            }, {
                value: '10',
                text: '款项未回'
            }];

        // 联营特批类型
        const associateAllowedType = [
            {
                value: '01',
                text: '合同扫描件未提供'
            }, {
                value: '00',
                text: '合同扫描件未提供且结算款未支付'
            }, {
                value: '10',
                text: '结算款未支付'
            }];

        const contractType = [
            {
                value: '1',
                text: '新增'
            }, {
                value: '2',
                text: '增购'
            }, {
                value: '3',
                text: '续签'
            }, {
                value: '4',
                text: '混签'
            }];

        // 直属联营 business_pattern [0, 1]
        // 正常特批 contract_status [0, 1]
        let $stockOutDialog;

        let $stockOutData;

        const close = () => {
            if ($stockOutDialog && _.isFunction($stockOutDialog.close)) {
                $stockOutDialog.close();
            }
        };

        const beforeStockOutShowInit = (stockOut = {}, $dialog, $dialogScope, $data) => {

            $stockOutDialog = $dialog;

            $stockOutData = $dialogScope.data;

            $dialogScope.stockOutRaw = _.cloneDeep(stockOut);

            $dialogScope.step = 1;

            $dialogScope.stockOut = stockOut;

            $dialogScope.xqProjectScope = [
                {
                    text: '已过期',
                    value: '3'
                }, {
                    text: '即将过期',
                    value: '2'
                }, {
                    text: '正常',
                    value: '1'
                }, {
                    text: '已禁用',
                    value: '0'
                }
            ];

            $dialogScope.selectedXqProjectScope = _.filter($dialogScope.xqProjectScope,
                (x, index) => index < $dialogScope.xqProjectScope.length - 2);

            $dialogScope.showXqProjectScope = () => _.some($data.products, {contractType: '3'});

            $dialogScope.next = () => {
                ++$dialogScope.step;
            };

            $dialogScope.prev = () => {
                --$dialogScope.step;
            };

            $dialogScope.today = moment(GET_SERVER_TIME()).format('YYYY-MM-DD');

            $data.order = {
                moneyStatus: (stockOut.order || {}).moneyStatus === undefined ? '1' : stockOut.order.moneyStatus
            };

            // 租户类型
            $data.order.tenantType = tenantType;

            // 租户类型默认值
            $data.order.currentTenantType = (stockOut.order || {}).isNewOrg === undefined
                ? tenantType[0]
                : _.find(tenantType, x => stockOut.order.isNewOrg === x.value);

            // 租户类型
            $dialogScope.stockOutType = stockOutType;

            $dialogScope.contractType = contractType;

            // 是否是新租户
            $dialogScope.isNewTenant = () => $data.order.currentTenantType && +$data.order.currentTenantType.value === 1;

            $dialogScope.isOldTenant = _.negate($dialogScope.isNewTenant);

            // 直属特批类型
            $dialogScope.directAllowedType = directAllowedType;

            // 联营特批类型
            $dialogScope.associateAllowedType = associateAllowedType;

            // 是否直属
            $dialogScope.isDirect = () => +$data.order['businessPattern'] === 1;

            // 是否联营
            $dialogScope.isAssociate = _.negate($dialogScope.isDirect);

            // 是否正常
            $dialogScope.isNormal = () => +$data.order['contractStatus'] === 1 && +$data.order['moneyStatus'] === 1;

            // 是否特批
            $dialogScope.isAllowed = _.negate($dialogScope.isNormal);

            $dialogScope.close = () => $dialog.close();

            $dialogScope.cache = {
                projects: {}
            };

            $dialogScope.contractsTransform = res => {
                return _.map(res.data.data || [], x => {
                    x['signAmount'] = (+x['signAmount']).toFixed(0);
                    x['signDate'] = (x['signDate'] || '').slice(0, 10);
                    return x;
                });
            };

            return stockOut;

        };

        const beforeStockOutShowSetValue = (stockOut = {}, $dialog, $dialogScope, $data) => {

            const beforeShow = $data => {

                if ($data) {

                    const stockOutTypeValue = () => {
                        const bp = $data.order['businessPattern'];
                        const cs = $data.order['contractStatus'];
                        const ms = $data.order['moneyStatus'];
                        if (+bp === 1 && +cs === 1 && +ms === 1) {
                            return 1;
                        } else if (+bp === 1) {
                            return 2;
                        } else if (+bp === 2 && +cs === 1 && +ms === 1) {
                            return 3;
                        } else {
                            return 4;
                        }
                    };
                    const allowedTypeValue = '' + $data.order['contractStatus'] + $data.order['moneyStatus'];

                    // 合同类型默认值
                    $dialogScope.currentStockOutType = _.find(stockOutType, x => +x.value === stockOutTypeValue());

                    // 直属特批类型默认值
                    $dialogScope.currentDirectAllowedType = _.find(directAllowedType, x => x.value === allowedTypeValue);

                    // 联营特批类型默认值
                    $dialogScope.currentAssociateAllowedType = _.find(associateAllowedType,
                        x => x.value === allowedTypeValue);

                } else {

                    // 合同类型默认值
                    $dialogScope.currentStockOutType = stockOutType[0];

                    // 直属特批类型默认值
                    $dialogScope.currentDirectAllowedType = directAllowedType[0];

                    // 联营特批类型默认值
                    $dialogScope.currentAssociateAllowedType = associateAllowedType[0];

                }

            };

            if (stockOut['order']) {

                let paths = ['promiseFulfilPrinciple', 'signPeopleId', 'adviserGuid'];
                const getUser = (data) => {
                    paths = _.filter(paths, x => !!data[x]);
                    return _(data).pick(paths).values().compact().value();
                };

                beforeShow(_.merge($data, stockOut));

                _.map($data.products, product => {
                    product.bindProjectNames = _(product.bindProject).map(x => (x.checked = true, x)).map('projName').value().join(',');
                    return product;
                });

                return $q.all(_.map(getUser($data.order), id => service.getUser({id}))).then(res => {
                    _.each(paths, (value, key) => {
                        $dialogScope[value] = res[key].data.data['userName'];
                        if (value === 'promiseFulfilPrinciple') {
                            $dialogScope.data.order.promiseFulfilPrinciple = res[key].data.data['userGuid'];
                            $dialogScope.data.order.promiseFulfilPrincipleName = res[key].data.data['userName'];
                        }
                        if (value === 'signPeopleId') {
                            $dialogScope.data.order.signPeopleId = res[key].data.data['userGuid'];
                            $dialogScope.data.order.signPeopleName = res[key].data.data['userName'];
                            $dialogScope.data.order.signPeoplePhone = res[key].data.data['mobilePhone'];
                            $dialogScope.data.order.signPeopleEmail = res[key].data.data['email'];
                        }
                        if (value === 'adviserGuid') {
                            $dialogScope.data.order.adviserGuid = res[key].data.data['adviserGuid'];
                            $dialogScope.data.order.adviserName = res[key].data.data['userName'];
                            $dialogScope.data.order.adviserTel = res[key].data.data['mobilePhone'];
                            $dialogScope.data.order.adviserMail = res[key].data.data['email'];
                        }

                    });
                    $dialogScope.customerName = $dialogScope.data.order.customerName;
                }).then(() => _.each(['contractCode', 'orgCode'], x => $dialogScope[x] = $data.order[x])).then(() => $dialogScope.$applyAsync());
            } else {
                beforeShow();
                return $q.resolve('');
            }
        };

        $scope.beforeStockOutShow = (stockOut = {}, $dialog, $dialogScope, $data) => {

            stockOut = beforeStockOutShowInit(stockOut, $dialog, $dialogScope, $data);

            beforeStockOutShowSetValue(stockOut, $dialog, $dialogScope, $data);

            setTimeout(() => {
                $dialogScope.resetDialog();
            }, 0);

        };

        /**
         * 复用
         */

        $scope.stockOutTpl = require('../dialog/stock_out.html');
        $scope.chTpl = require('../dialog/ch.html');
        $scope.fqTpl = require('../dialog/fq.html');
        $scope.stepsTpl = require('../dialog/steps.html');
        $scope.createTenantTpl = require('../dialog/create_tenant.html');
        $scope.createAuthTpl = require('../dialog/create_auth.html');

        $scope.canOperate = (responseUserId) => ($scope.userInfo || {}).userGuid === responseUserId;

        $scope.beforeDhShow = ($dialogScope, name) => {

            $dialogScope.name = name;

        };

        $scope.beforeStepsShow = function (item, $dialog, $dialogScope) {

            $dialogScope.close = () => $dialog.close();

            service.getApproveRecord({}, item.id).then(res => $dialogScope.steps = res.data.data);

        };

        $scope.qr = function (orderId) {

            service.qr({}, orderId).then(() => $rootScope.$emit('refreshTodo')).then(() => {
                close();
                ui.showSucTip('确认成功');
            });

        };

        $scope.sp = function (orderId) {

            service.sp({}, orderId).then(() => $rootScope.$emit('refreshTodo')).then(() => {
                close();
                ui.showSucTip('审批成功');
            });

        };

        $scope.dh = function (data, orderId) {

            service.dh(data, orderId).then(() => $rootScope.$emit('refreshTodo')).then(() => {
                close();
                ui.showSucTip('打回成功');
            });

        };

        $scope.orderHt = function (orderId) {

            service.orderHt({delivery_guid: orderId})
                .then(() => $rootScope.$emit('refreshTodo'))
                .then(() => {
                    close();
                    ui.showSucTip('回退成功');
                });

        };

        $scope.beforeCreateTenantShow = function (stockOut, $dialog, $dialogScope) {

            $dialogScope.data.orderCode = stockOut.order.orderCode;
            $dialogScope.data.friendlyName = stockOut.order.orgName;
            $dialogScope.data.uniqueName = stockOut.order.orgCode;

            function formatCustomer(repo) {
                if (repo.loading) return repo.text;

                return repo.text;
            }

            function formatCustomerSelection(repo) {
                return repo.text;
            }

            // 客户下拉框处理
            $dialogScope.ddlConfigCustomer = {
                allowClear: false,
                placeholder: '顶级客户简称',
                ajax: {
                    url: "/api/index.php?r=erp-interface/get-erp-customer-info",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function (i, d) {
                                d.text = d.CstName;
                                d.id = d.CSTGUID;
                            });
                        }
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                },
                minimumInputLength: 1,
                onchange2: function (newVal) {
                    $dialogScope.data.TopCstName = newVal.DjCstName;
                    $dialogScope.data.CstGuid = newVal.CSTGUID;
                },
                formatResult: formatCustomer,
                formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
            };


            service.getRDSDataInstanceList().then(res => $dialogScope.rdsList = res.data.data);

        };

        $scope.createTenant = (tenant) => {

            service.createTenant({
                orderCode: tenant.orderCode,
                friendlyName: tenant.friendlyName,
                uniqueName: tenant.uniqueName,
                email: tenant.email,
                instanceId: tenant.instanceId,
                CstGuid: tenant.CstGuid,
                TopCstName: tenant.TopCstName,
                USE_FORM_DATA: true
            }).then(() => $rootScope.$emit('refreshTodo')).then(res => ui.showSucTip('新增租户成功')).then(close);

        };

        $scope.beforeCreateAuthShow = function (stockOut, $dialog, $dialogScope) {

            const categoryList = [
                {name: '合同未归档', value: '1'},
                {name: '款项未回', value: '2'},
                {name: '合同未归档且款项未回', value: '3'},
                {name: '结算款未支付', value: '4'},
                {name: '合同扫描件未提供', value: '5'},
                {name: '合同扫描件未提供且结算款未支付', value: '6'}
            ];

            ui.loading('', '正在加载…');

            $dialogScope.data.ContractNum = stockOut.order.contractCode;
            $dialogScope.data.orgId = stockOut.order.orgId;
            $dialogScope.data.orderCode = stockOut.order.orderCode;
            $dialogScope.data.PartyA = stockOut.order.customerFullName;
            $dialogScope.data.BeginOn = stockOut.order.rentStartDate;

            service
                .getAreaList({}, stockOut.order.orderCode)
                .then(function (res) {
                    const tabData = _.map(res.data.data, x => ({
                        value: x.areaId + '',
                        name: x.areaName
                    }));
                    $dialogScope.items = tabData;
                    if (tabData.length) {
                        $dialogScope.data.area_id = stockOut.order.areaId;
                    }
                });

            $dialogScope.categoryList = categoryList;

            if (!$dialogScope.data.EstablishTime) {
                $dialogScope.data.establish_time = moment(GET_SERVER_TIME()).format('YYYY-MM-DD');
            } else {
                $dialogScope.data.establish_time = moment($dialogScope.data.EstablishTime).format('YYYY-MM-DD');
            }

            $dialogScope.ddlConfigPrinciple = {
                ajax: {
                    url: '/api/index.php?r=/erp-interface/get-users',
                    dataType: 'json',
                    delay: 250,
                    data: function (term, page) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (data, page) {
                        return {
                            results: data.data
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                },
                minimumInputLength: 1,
                templateResult: function (data) {
                    return data;
                },
                templateSelection: function (data) {
                    return data;
                },
                onchange2: function (newVal) {
                    $dialogScope.data.promiseFulfilPrinciple = newVal.id;
                }
            };

            $dialogScope.rentStartDateChange = (item) => {
                if (item.begin_on) {
                    item.end_on = moment(item.begin_on).add(item.rent_period, 'month').format('YYYY-MM-DD');
                }
            };

            service.getAllPackages({}, stockOut.order.subOrderId).then(function (data) {

                data = data.data.data;

                data = mapSnakeCase(data);

                for (const key in data) {
                    if (data.hasOwnProperty(key)) {
                        data[key].total_num = data[key].count || 0;
                    }
                }

                $dialogScope.data.ContractType = stockOut.order.contractStatus;

                $dialogScope.data.authType = (+stockOut.order['contractStatus'] === 1
                    && +stockOut.order['moneyStatus'] === 1) ? '1' : '4';

                // 【流程中心】类型为特批时，新增授权时，特批类型、承受兑现时间、兑现责任人、以及授权项目数都需要默认过来。
                if ($dialogScope.data.authType === '4') {

                    const allowedTypeValue = '' + stockOut.order['contractStatus'] + stockOut.order['moneyStatus'];

                    if (stockOut.order['businessPattern'] === '1') {
                        _.each({
                            '01': '1',
                            '00': '3',
                            '10': '2'
                        }, (v, k) => {
                            if (allowedTypeValue === k) {
                                $dialogScope.data.category = v;
                            }
                        });
                    } else if (stockOut.order['businessPattern'] === '2') {
                        _.each({
                            '01': '5',
                            '00': '6',
                            '10': '4'
                        }, (v, k) => {
                            if (allowedTypeValue === k) {
                                $dialogScope.data.category = v;
                            }
                        });
                    }

                    $dialogScope.data.promiseFulfilTime = (stockOut.order.promiseFulfilTime || '').slice(0, 10);

                    $dialogScope.data.promiseFulfilPrinciple = stockOut.order.promiseFulfilPrinciple;

                    service.getUser({id: stockOut.order.promiseFulfilPrinciple})
                        .then(res => {

                            $dialogScope.data.promiseFulfilPrincipleName = res.data.data['userName'];

                            setTimeout(function () {
                                const $pfp = $('#promiseFulfilPrinciple');
                                if ($pfp.length) {
                                    $pfp.data('select2')
                                        .updateSelection({text: $dialogScope.data.promiseFulfilPrincipleName || ''});
                                }
                            }, 0);

                        });
                }

                _.each(data, $dialogScope.rentStartDateChange);

                $dialogScope.data.packages = data;

                setTimeout(function () {
                    $dialog.reset();
                }, 0);

            });

            $dialogScope.categoryList = categoryList;

        };

        $scope.createAuth = (contract, organizationId) => {

            let packages = contract.packages;

            packages = _.map(packages, pkg => {
                pkg.package_id = pkg.id;
                pkg.IsQdAdvanced = pkg.is_qd_advanced;
                return pkg;
            });

            return service.createAuth({
                order_code: contract.orderCode,
                contract_id: contract.contractId,
                contract_num: contract.ContractNum,
                party_a: contract.PartyA,
                contract_type: contract.ContractType,
                begin_on: contract.BeginOn,
                end_on: contract.EndOn,
                area_id: contract.area_id,
                organization_id: organizationId,
                auth_info: packages,
                establish_time: contract.establish_time,
                authType: contract.authType,
                category: contract.category,
                promiseFulfilTime: contract.promiseFulfilTime,
                actualFulfilTime: contract.actualFulfilTime,
                promiseFulfilPrinciple: contract.promiseFulfilPrinciple,
                promiseFulfilPrincipleName: contract.promiseFulfilPrincipleName,
                USE_FORM_DATA: true
            })
                .then(() => $rootScope.$emit('refreshTodo'))
                .then(res => ui.showSucTip('新增授权成功'))
                .then(close);

        };

        /**
         * 打开弹窗先请求 view
         */
        $scope.warpViewPromise = (stockOut, ...others) => (originFn) => {
            service.view({sub_order_id: stockOut.id})
                .then(res => res.data.data)
                .then(data => originFn(data, ...others));

        };

    }]);

export default app;
